package com.etime.shycourse.controller.orders;

import com.etime.shy.common.BaseMessage;
import com.etime.shy.common.ListMessage;
import com.etime.shy.common.PojoMessage;
import com.etime.shycourse.controller.wx.rss.TemplateData;
import com.etime.shycourse.controller.wx.rss.WXRSSData;
import com.etime.shycourse.controller.wx.rss.WXRSSService;
import com.etime.shycourse.orde.dto.OrderDetailDto;
import com.etime.shycourse.orde.dto.OrderDetails;
import com.etime.shycourse.orde.pojo.Orderdetail;
import com.etime.shycourse.orde.pojo.Orders;
import com.etime.shycourse.orde.services.interfaces.WxOrdersServices;
import com.etime.shycourse.pojo.SysUser;
import com.etime.shycourse.services.interfaces.SysUserService;
import com.etime.shycourse.wx.applets.pojo.Course;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wb
 * @since 2022-01-10
 */
@Api(tags = "微信订单管理数据接口")
@RestController
@RequestMapping("/wx/orders")
public class WXOrdersController {
    @Autowired
    private WxOrdersServices services;
    //发送订阅消息服务器类
    @Autowired
    private WXRSSService wxrssService;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 测试时 必须传 orderuserid 其他根据前端需要
     * 2022-02-10 16:15:29 改为 token
     * <p></p>
     * 其他后台的默认设置:
     * 设置订单创建人 ordercreateuserid 登录用户id
     * 设置购买人姓名 当前登录人姓名 orderusertruename
     * 设置订单创建人姓名 ordercreatename 登录用户id
     * <p>
     * 设置订单明细表的 orderid 为订单orderid
     * 设置订单支付状态 orderstate 默认1 -待支付
     * <p>
     * 不传值
     * 默认：
     * 订单最后修改时间	orderupdatetime	datetime	当前时间
     * 订单创建时间   ordercreatetime	datetime	当前时间
     * 订单号	orderno	varchar(64)	算法生成 雪花id
     * 订单创建原因	ordercreatereason	varchar(255)	默认：用户下单
     **/
    @ApiOperation("创建订单 返回订单id")
    @PostMapping("/insert")
    @ApiImplicitParams({
            @ApiImplicitParam("orderdetail 、orders中的字段必须传一个，其他有根据前端需要传值,默认值的字段 可不传值"),
            @ApiImplicitParam(name = "orderuserid", value = "测试时 必传 用户id 例如-1 14"),
            @ApiImplicitParam(name = "ordercreateuserid", value = "不传 设置订单创建人 登录用户id"),
            @ApiImplicitParam(name = "orderusertruename", value = "不传 设置购买人姓 登录用户姓名"),
            @ApiImplicitParam(name = "ordercreatename", value = "不传 设置订单创建人姓名 登录用户姓名"),
            @ApiImplicitParam(name = "orderupdatetime", value = "不传 订单最后修改时间"),
            @ApiImplicitParam(name = "orderno", value = "不传 订单号"),
            @ApiImplicitParam(name = "orderstate", value = "可不传  默认1 -待支付"),
            @ApiImplicitParam(name = "ordercreatereason", value = "可传 有默认值：用户下单"),
            @ApiImplicitParam(name = "orderid", value = "不传 后台交互自动生成"),
    })
    public BaseMessage insertOrderDetails(@RequestBody OrderDetails orderDetails, HttpServletRequest request) {
        BaseMessage msg = new BaseMessage ();
        String token = request.getHeader ("token");
        if (token == null || token.equals ("")) {
            msg.setCode (-2);
            msg.setMsg ("未获取到用户信息；可能登录超时");
            return msg;
        }
        int OrderId = services.insertOrderDetails (orderDetails, token);

        if (OrderId != 0) {
            msg.setCode (OrderId);
            msg.setMsg ("创建订单成功");
        } else {
            msg.setCode (0);
            msg.setMsg ("购买课程失败,可能原因：网络延迟、您已购买或者已创建订单！");
        }
        return msg;
    }

    @ApiOperation("购物车中创建订单 返回订单id")
    @PostMapping("/ByCar/insert")
    @ApiImplicitParams({
            @ApiImplicitParam("orderdetail 、orders中的字段必须传一个，其他有根据前端需要传值,默认值的字段 可不传值"),
            @ApiImplicitParam(name = "orderuserid", value = "测试时 必传 用户id 例如-1 14"),
            @ApiImplicitParam(name = "ordercreateuserid", value = "不传 设置订单创建人 登录用户id"),
            @ApiImplicitParam(name = "orderusertruename", value = "不传 设置购买人姓 登录用户姓名"),
            @ApiImplicitParam(name = "ordercreatename", value = "不传 设置订单创建人姓名 登录用户姓名"),
            @ApiImplicitParam(name = "orderupdatetime", value = "不传 订单最后修改时间"),
            @ApiImplicitParam(name = "orderno", value = "不传 订单号"),
            @ApiImplicitParam(name = "orderstate", value = "可不传  默认1 -待支付"),
            @ApiImplicitParam(name = "ordercreatereason", value = "可传 有默认值：用户下单"),
            @ApiImplicitParam(name = "orderid", value = "不传 后台交互自动生成"),
    })
    public BaseMessage insertOrderDetailsByCar(@RequestBody OrderDetails orderDetails, HttpServletRequest request) {
        BaseMessage msg = new BaseMessage ();
        String token = request.getHeader ("token");
        if (token == null || token.equals ("")) {
            msg.setCode (-2);
            msg.setMsg ("未获取到用户信息；可能登录超时");
            return msg;
        }
        int OrderId = services.insertOrderDetailsByCar (orderDetails, token);
        if (OrderId > 0) {
            msg.setCode (OrderId);
            msg.setMsg ("创建订单成功");
        } else if (OrderId == -1) {
            //  已经购买完成就不进行购买 返回 -1
            msg.setCode (0);
            msg.setMsg ("购买课程失败,原因：您已经购买完成！");
        } else {
            msg.setCode (0);
            msg.setMsg ("购买课程失败,可能原因：网络延迟、您已购买或者已创建订单！");
        }
        return msg;
    }

    /**
     * 2022 - 02 - 10 16:41:37
     * 判断是否已经购买其课程(订单为 创建、完成)
     *
     * @param dto
     * @return boolean
     */
    @ApiOperation("判断是否已经购买其课程 携带 token")
    @GetMapping("/iFBuyCourse")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "odcourseid", value = "商品课程id"),
            @ApiImplicitParam(name = "odchapterid", value = "商品章id"),
            @ApiImplicitParam(name = "odlessonid", value = "商品课时id"),
    })
    public BaseMessage iFBuyCourse(HttpServletRequest request, OrderDetailDto dto) {
        BaseMessage msg = new BaseMessage ();
        String token = request.getHeader ("token");
        if (token == null || token.equals ("")) {
            msg.setCode (-2);
            msg.setMsg ("未获取到用户信息；可能登录超时");
            return msg;
        }
        List<Integer> buyCourse = services.iFBuyCourse (dto, token);
        if (buyCourse.size () != 0) {
            msg.setCode (1);
            msg.setMsg ("已经购买其课程,或已经创建了订单");
        } else {
            msg.setCode (0);
            msg.setMsg ("没有购买课程！");
        }
        return msg;
    }

    /**
     * 根据订单id 获取订单详情
     * selectOrderDetailsByOrderId
     *
     * @param orderId
     * @return Orders
     */
    @ApiOperation("根据订单id 获取订单详情")
    @GetMapping("/OrderDetails/get/{orderId}")
    public PojoMessage<Orders> selectOrderDetailsByOrderId(@PathVariable Integer orderId) {
        PojoMessage<Orders> msg = new PojoMessage<> ();
        Orders data = services.selectOrderDetailsByOrderIds (orderId);
        if (data != null) {
            msg.setCode(1);
            msg.setData(data);
        } else {
            msg.setCode(0);
            msg.setMsg("没有找到订单详情信息");
        }
        return msg;
    }

    // 数据查询：通过用户id-->订单+订单明细
    @ApiOperation("根据token获取 登录用户的我的订单详情")
    @ApiImplicitParam("用户的token，可以不用传递。但是必须要在请求头中有token属性,orderState:订单状态 -1--全部 1--创建 2--完成 3--关闭 4--退款 ")
    @GetMapping("/OrderDetails/ordersList/get/{orderState}")
    public ListMessage<Orders> getCurrentUser(@PathVariable Integer orderState, HttpServletRequest request) {
        ListMessage<Orders> msg = new ListMessage<>();
        String token = request.getHeader("token");
        if (token == null || token.equals("")) {
            msg.setCode(-2);
            msg.setMsg("未获取到用户信息；可能登录超时");
            return msg;
        }
        List<Orders> data = services.selectOrderDetailsByUserId (token, orderState);
        if (data != null) {
            msg.setCode (1);
            msg.setDatalist (data);
        } else {
            msg.setCode (0);
            msg.setMsg ("没有找到订单详情信息");
        }
        return msg;
    }

    @ApiOperation("关闭订单 根据订单id (小程序取消订单)")
    @PostMapping("/upDataOrder/{orderId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "订单状态 没有传 则后台添加 orderstate = 3,默认的值由：后台根据token获取再添加"),
    })
    public BaseMessage updataOrderById(HttpServletRequest request, @PathVariable Integer orderId) {
        BaseMessage msg = new BaseMessage ();
        String token = request.getHeader ("token");
        if (token == null || token.equals ("")) {
            msg.setCode (-2);
            msg.setMsg ("未获取到用户信息；可能登录超时");
            return msg;
        }
        Orders order = new Orders ();
        order.setOrderid (orderId);
        int i = services.upDataOrderById (token, order);
        if (i != 0) {
            msg.setCode (1);
            msg.setMsg ("关闭订单成功");
        } else {
            msg.setCode (0);
            msg.setMsg ("关闭订单失败！");
        }
        return msg;
    }

    // 临时后台管理用创建订单
    @ApiOperation("返回int 成功 =1 失败=0 临时后台管理用创建订单")
    @PostMapping("/Temporary/Orderdetail/insert")
    public BaseMessage insetCourseTemporary(@RequestBody OrderDetails dto, HttpServletRequest request) {
        BaseMessage msg = new BaseMessage ();
        String token = request.getHeader ("token");
        if (token == null || token.equals ("")) {
            msg.setCode (-2);
            msg.setMsg ("未获取到用户信息；可能登录超时");
            return msg;
        }
        int i = services.insetOrderdetailList (dto, token);

        if (i != 0) {
            msg.setCode (i);
            msg.setMsg ("创建订单明细成功");
            //发送订阅消息
            sendRSS (dto.getOrderuserid (), dto);
        } else {
            msg.setCode (0);
            msg.setMsg ("购买明细失败,可能原因：网络延迟、您已购买或者已创建订单！");
        }
        return msg;
    }

    /**
     * 发送领取课程订阅消息
     *
     * @param userid       用户id
     * @param orderDetails 购买的课程列表
     */
    private void sendRSS(Integer userid, OrderDetails orderDetails) {
        SysUser user = sysUserService.selectSysUserById (userid);
        if (user != null) {
            if (user.getOpenid () != null && !user.getOpenid ().equalsIgnoreCase ("")) {
                //发送消息
                WXRSSData wxrssData = new WXRSSData ();
                wxrssData.setTouser (user.getOpenid ());
                wxrssData.setPage ("pages/member/service/mycourse");
                wxrssData.setTemplate_id ("JLhOkbE52OOA_vX6TWAoqnG7GDCl4ls_Wu4F6SLp-Pk");
                Map<String, TemplateData> params = new HashMap<> ();
                params.put ("thing1", new TemplateData ("优才学习包"));
                List<Orderdetail> orderdetailList = orderDetails.getOrderdetailList ();
                params.put ("character_string2", new TemplateData (orderdetailList.size () + ""));
                params.put ("thing3", new TemplateData ("请到树蕙元我的课程中查看您的优才学习包"));
                SimpleDateFormat df = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
                String time = df.format (new Date ());
                params.put ("time8", new TemplateData (time));
                wxrssData.setData (params);
                String rtn = wxrssService.pushmessage (wxrssData);
            }
        } else {
            System.out.println ("用户不存在");
        }
    }


    // 数据查询：通过用户id-->从订单，订单明细，关联到课程表进行查询。 我的课程数据接口
    @ApiOperation("根据token获取 我的已购课程数据接口")
    @ApiImplicitParam("用户的token，可以不用传递 ")
    @GetMapping("/OrderDetails/CourseList/Purchased/get")
    public ListMessage<Course> getCurrentUserCourse(HttpServletRequest request) {
        ListMessage<Course> msg = new ListMessage<> ();
        String token = request.getHeader ("token");
        if (token == null || token.equals ("")) {
            msg.setCode (-2);
            msg.setMsg ("未获取到用户信息；可能登录超时");
            return msg;
        }
        List<Course> data = services.searchAllBy (token);
        if (data != null) {
            msg.setCode (1);
            msg.setDatalist (data);
        } else {
            msg.setCode (0);
            msg.setMsg ("没有找到已购课程数据接口");
        }
        return msg;
    }


    /**
     * 判断用户有没有
     * 未购买的订单有返回订单id
     * 当用户 有订单存在 返回第一个订单id
     * 没有返回0
     *
     * @return int
     */
    @ApiOperation("(携带token)当用户,有订单存在,返回第一个订单id ")
    @GetMapping("/buyCar/user")
    public BaseMessage selectByCatOrdersByUserId(HttpServletRequest request) {
        BaseMessage msg = new BaseMessage ();
        String token = request.getHeader ("token");
        if (token == null || token.equals ("")) {
            msg.setCode (-2);
            msg.setMsg ("未获取到用户信息；可能登录超时");
            return msg;
        }
        int rtn = services.selectByCatOrdersByUserId (token);
        if (rtn > 0) {
            msg.setCode (rtn);
            msg.setMsg ("有订单存在,已返回了第一个订单id");
        } else {
            msg.setCode (0);
            msg.setMsg ("没有订单存在");
        }
        return msg;
    }

    /**
     * 判断订单状态数据接口(add by zw)
     *
     * @param orderid 订单id
     * @return
     */
    @ApiOperation("根据订单id查询订单状态")
    @ApiImplicitParam(name = "orderid", value = "订单id")
    @GetMapping("/checkstate/{orderid}")
    public BaseMessage checkOrderState(@PathVariable Integer orderid) {
        BaseMessage msg = new BaseMessage ();
        Orders orders = services.selectOrdersById (orderid);
        if (orders != null) {
            msg.setCode (orders.getOrderstate ());
            if (orders.getOrderstate () == 1) {
                msg.setMsg ("订单未支付，需要进行支付");
            } else if (orders.getOrderstate () == 2) {
                msg.setMsg ("订单已完成，请勿重复支付");
            } else {
                msg.setMsg ("订单已关闭，如需购买，请重新下单");
            }
        } else {
            msg.setCode (0);
            msg.setMsg ("订单不存在");
        }
        return msg;
    }
}

